package com.ourchem.framework.web.service;

import cn.hutool.core.lang.Validator;
import com.ourchem.bus.domain.SimpleEmailEntity;
import com.ourchem.bus.service.impl.mailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import com.ourchem.common.constant.Constants;
import com.ourchem.common.constant.UserConstants;
import com.ourchem.common.core.domain.entity.SysUser;
import com.ourchem.common.core.domain.model.RegisterBody;
import com.ourchem.common.core.redis.RedisCache;
import com.ourchem.common.exception.user.CaptchaException;
import com.ourchem.common.exception.user.CaptchaExpireException;
import com.ourchem.common.utils.MessageUtils;
import com.ourchem.common.utils.SecurityUtils;
import com.ourchem.framework.manager.AsyncManager;
import com.ourchem.framework.manager.factory.AsyncFactory;
import com.ourchem.system.service.ISysConfigService;
import com.ourchem.system.service.ISysUserService;

/**
 * 注册校验方法
 *
 * @author ourchem
 */
@Component
public class SysRegisterService
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private mailServiceImpl mailService;

    @Value("${LoginURL}")
    private String LoginURL;

    /**
     * 注册
     * 邮箱，手机号，企业，密码,验证码
     */
    public String register(RegisterBody registerBody) {
        String msg = "",
        username = registerBody.getUsername(),
        password = registerBody.getPassword(),
        email = registerBody.getEmail(),
        phonenumber = registerBody.getPhonenumber(),
        enpName = registerBody.getEnpName();
        SysUser sysUser1 = new SysUser();
        sysUser1.setEmail(username);
        sysUser1.setPhonenumber(phonenumber);
        sysUser1.setEnpName(enpName);

        boolean captchaOnOff = configService.selectCaptchaOnOff();
        // 验证码开关
//        if (!captchaOnOff) {
//            validateCaptcha(username, registerBody.getCode(), registerBody.getUuid());
//        }

//        if (StringUtils.isEmpty(username))
//        {
//            msg = "用户名不能为空";
//        } else if (StringUtils.isEmpty(email)) {
//            msg = "用户邮箱不能为空";
//        } else if (StringUtils.isEmpty(phonenumber)) {
//            msg = "用户手机号不能为空";
//        } else if (StringUtils.isEmpty(enpName)) {
//            msg = "用户企业名称不能为空";
//        }

        if (StringUtils.isEmpty(username)) {
            msg = "用户名不能为空";
//        else
//            if (StringUtils.isEmpty(email)) {
//            msg = "用户邮箱不能为空";
        } else if (StringUtils.isEmpty(password)) {
            msg = "用户密码不能为空";
        }
//        else if (!Validator.isEmail(email)) {
//            msg = "邮箱格式不正确";
//        }
        else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            msg = "密码长度必须在5到20个字符之间";
        }
        else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(sysUser1))) {
            msg = "保存用户'" + username + "'失败，用户已存在";
        }
        else {
            SysUser sysUser = new SysUser();
            //账号==邮箱
            sysUser.setUserName(username);
            sysUser.setEmail(username);
            sysUser.setPhonenumber(phonenumber);
            sysUser.setEnpName(enpName);
            sysUser.setNickName(email);
            sysUser.setPassword(SecurityUtils.encryptPassword(registerBody.getPassword()));
            //注册默认账号为企业用户
            Long[] longs = new Long[1];
            longs[0] = Long.valueOf(2);//默认pt用户
            sysUser.setRoleIds(longs);//连表将RoleIds写入sys_user_role中
            sysUser.setRoleId(2L);
            int row = userService.insertUser(sysUser);
            if (row != 1) {
                msg = "注册失败,请联系系统管理人员";
            } else {
                SimpleEmailEntity simpleEmailEntity = new SimpleEmailEntity();
                simpleEmailEntity.setContent("尊敬的用户：\n" +
                        "\n" +
                        "       您好，恭喜您注册成功培训系统中心平台账号，账号信息为，登录账号："+sysUser.getEmail()+"，密码为："+password+ "，平台登录地址为:"+LoginURL+"\n" +
                        "\n" +
                        "       谢谢");
                simpleEmailEntity.setSubject("注册成功");
                String[] strings = new String[]{email};
//                simpleEmailEntity.setTos(strings);
//                mailService.sendSimpleMail(simpleEmailEntity);
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER,
                        MessageUtils.message("user.register.success")));
            }
        }
        return msg;
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            throw new CaptchaException();
        }
    }
//已存在邮箱验证 checkUserNameUnique

/*    public String email(String email) {
        String msg = "";
        SysUser sysUser = new SysUser();
        sysUser.setEmail(email);
        if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(sysUser))) {
            msg = "注册邮箱已存在";
        }
        return msg;
    }*/
}
